import * as vscode from 'vscode';
import * as fs from 'fs';
import { JGEViewProvider } from './JGEViewProvider';
import { WebSocketManager } from './WebSocketManager';
import { HighlightManager } from './HighlightManager';
import { ServerManager } from './ServerManager';
import { FileWatcher } from './FileWatcher';
import { MessageHandler } from './MessageHandler';

export function activate(context: vscode.ExtensionContext) {
    console.log('JGE-RS扩展已激活');

    const provider = new JGEViewProvider(context.extensionUri);
    let webSocketManager: WebSocketManager;
    let highlightManager: HighlightManager;
    let serverManager: ServerManager;
    let fileWatcher: FileWatcher;
    let messageHandler: MessageHandler;

    // 创建输出通道
    const outputChannel = vscode.window.createOutputChannel('JGE Server');
    context.subscriptions.push(outputChannel);

    // 注册视图提供者
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider(JGEViewProvider.viewType, provider)
    );

    // 创建诊断集合
    const diagnosticCollection = vscode.languages.createDiagnosticCollection('jge-rs');
    context.subscriptions.push(diagnosticCollection);

    // 创建高亮管理器
    highlightManager = new HighlightManager(context.extensionUri, diagnosticCollection);

    // 创建消息处理器
    messageHandler = new MessageHandler({
        highlightManager: highlightManager
    });

    // 创建服务端管理器
    serverManager = new ServerManager(outputChannel, (status) => {
        provider.setServerStatus(status);
    });

    // 创建文件监视器
    fileWatcher = new FileWatcher((eventType, filePath) => {
        webSocketManager.sendMessage({
            event: eventType,
            file: filePath,
            time: new Date().toISOString()
        });
    });

    // 确保图标资源存在
    const warningIconPath = context.asAbsolutePath('warning.svg');
    if (!fs.existsSync(warningIconPath)) {
        fs.writeFileSync(warningIconPath, `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="red">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
            </svg>
        `);
    }

    // 获取配置的服务器地址
    const config = vscode.workspace.getConfiguration('jge-rs');
    const serverAddress = config.get<string>('server', 'ws://127.0.0.1:8080/vscode');
    const secret = config.get<string>('secret', '123456789');

    // 创建WebSocket管理器
    webSocketManager = new WebSocketManager(
        serverAddress,
        secret,
        (message) => messageHandler.handleMessage(message),
        (status) => {
            provider.setStatus(status);
        }
    );

    // 注册命令
    const toggleConnectionCommand = vscode.commands.registerCommand('jge-rs.toggleConnection', () => {
        if (webSocketManager.isConnected()) {
            webSocketManager.disconnect();
        } else {
            webSocketManager.enableAutoReconnect();
            webSocketManager.connect();
        }
    });
    context.subscriptions.push(toggleConnectionCommand);

    const toggleServerCommand = vscode.commands.registerCommand('jge-rs.toggleServer', () => {
        serverManager.toggleServer();
    });
    context.subscriptions.push(toggleServerCommand);

    const sendDebugCommand = vscode.commands.registerCommand('jge-rs.sendDebug', (content: string) => {
        if (webSocketManager.sendMessage({ "cmd": "script", "script": content })) {
            vscode.window.showInformationMessage('调试信息已发送');
        } else {
            vscode.window.showErrorMessage('WebSocket未连接，无法发送调试信息');
        }
    });
    context.subscriptions.push(sendDebugCommand);

    const closeCurrentHighlight = vscode.commands.registerCommand('JGE-RS.closeHighlight', () => {
        const activeEditor = vscode.window.activeTextEditor;
        if (activeEditor) {
            highlightManager.clearHighlight(activeEditor.document.uri.fsPath);
        }
    });
    context.subscriptions.push(closeCurrentHighlight);

    // 初始连接
    webSocketManager.connect();

    // 清理资源
    context.subscriptions.push({
        dispose: () => {
            fileWatcher.dispose();
            webSocketManager.dispose();
            highlightManager.dispose();
            serverManager.dispose();
            outputChannel.dispose();
            vscode.window.showInformationMessage('[已关闭] JGE-RS vscode开发工具');
        }
    });
}

export function deactivate() { }
